<script setup lang="ts">
import { ElButton, ElInput } from 'element-plus'
import { useRequest } from 'ahooks-vue'
import { ref } from 'vue'
import SvgIcon from '@/components/SvgIcon/index.vue'
import { getCodePhone } from '@/api/login'

const props = defineProps<{ phone?: string }>()

const modelValue = defineModel<string>()
const time = ref(60)
const timer = ref<NodeJS.Timeout>()

const { run: handleGetCode, loading } = useRequest(
  async () => {
    await getCodePhone(props.phone!)
    time.value = 59
    timer.value = setInterval(() => {
      time.value -= 1
      if (time.value <= 0) {
        clearInterval(timer.value)
        timer.value = void 0
      }
    }, 1000)
  },
  { manual: true },
)
</script>

<template>
  <div class="flex mb-2">
    <ElInput v-model="modelValue" :maxlength="5" type="text" placeholder="验证码" size="large" class="flex-1 mr-2">
      <template #prefix>
        <SvgIcon icon-class="validCode" class="el-input__icon input-icon" />
      </template>
    </ElInput>
    <ElButton :loading="loading" :disabled="!phone || Boolean(timer)" size="large" type="primary" class="w-[6rem]" @click="handleGetCode">
      {{ timer ? time : '获取验证码' }}
    </ElButton>
  </div>
</template>

<style scoped lang="scss">

</style>
